package org.itboys.admin.service.lasted.process;



import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.lasted.SystemUser;
import org.itboys.admin.entity.lasted.process.SystemProcess;
import org.itboys.admin.entity.lasted.process.SystemProcessDetail;
import org.itboys.admin.entity.lasted.process.SystemProcessTemplate;
import org.itboys.admin.entity.lasted.process.SystemProcessTemplateNode;
import org.itboys.admin.service.lasted.SystemUserService;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2017年2月27日
 * 联系方式 ：empty90911@126.com
 * 描述：系统_流程_主体_service
 */
@Service
public class SystemProcessService extends BaseMongoService<SystemProcess> {
    @Autowired
    private SystemProcessTemplateService templateService;
    @Autowired
    private SystemProcessTemplateNodeService templateNodeService;
    @Autowired
    private SystemProcessDetailService processDetailService;
    @Autowired
    private SystemUserService userService;



    @Resource(name = "adminDS")
    private MongoDataSource ds;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return ds;
    }

    @Override
    protected Class<SystemProcess> getEntityClass() {
        return SystemProcess.class;
    }

    /**
     *开启流程
     * @param templateKey 流程模板的KEY
     * @param outClassName，业务对象的类名
     * @param outClassId 业务对象的ID主键
     */
    public void  startProcess(String templateKey,String outClassName,Long outClassId,String outClassNumber){
        //先找到模板
        Map<String,Object> param =new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("key",templateKey);
        List<SystemProcessTemplate> templates = templateService.list(param);
        if(ListUtil.isNotNull(templates)){
            SystemProcessTemplate template=templates.get(0);



            param.clear();
            param.put("isDeleted",0);
            param.put("templateId",template.getId());
            param.put("sort","sequence");
            param.put("order","ASC");
            //查询流程模板配置的人员信息。按顺序查出
            List<SystemProcessTemplateNode> templateNodes = templateNodeService.list(param);

            //实例化审核流程信息
            SystemProcess process = new SystemProcess(generateNumber("PRO"), template.getId(), template.getProcessTitle()+outClassNumber,
                    template.getProcessDesc(), template.getProcessType(),outClassName,outClassId,1,templateNodes.get(0).getUserId());
            super.save(process);
            param.clear();
            List<Long> userIds = new ArrayList<Long>();
            for(SystemProcessTemplateNode templateNode:templateNodes){
                userIds.add(templateNode.getUserId());
            }
            param.put("isDeleted",0);
            param.put("id in",userIds);
            List<SystemUser> users = userService.list(param);
            List<SystemProcessDetail> processDetails = new ArrayList<SystemProcessDetail>();
          //  Integer isCurrent=0;//是否当前节点
          //  Integer isFinal=0;//是否终点
            //流程当前节点归属用户ID
           // Long currentUserId=0l;
            for(int i =0;i<templateNodes.size();i++){
                SystemProcessTemplateNode  templateNode=templateNodes.get(i);
            //for(SystemProcessTemplateNode templateNode:templateNodes){
                for(SystemUser user:users){
                    if(templateNode.getUserId().longValue()==user.getId()){


                        SystemProcessDetail processDetail =
                                new SystemProcessDetail(
                                        process.getId(), templateNode.getUserId(),user.getName(),templateNode.getSequence(),
                                        null,1,process.getTitle(),
                                        template.getDesc(),process.getType(),outClassName,outClassId);
                        processDetails.add(processDetail);
                        break;
                    }
                }
            }
            processDetailService.batchSave(processDetails);

        }


    }
    /**
     * 操作（审核）流程
     * @param
     */
    /**
     *
     * @param outClassName 业务对象的类名
     * @param outClassId 业务对象的ID主键
     * @param handleMsg 审核信息
     * @param isAgree 审核操作。true/false
     * @return -4，当前审核节点用户信息不匹配，-3,已经操作过（错误），-2找不到流程记录（错误），0审核成功，但流程未结束,1审核成功，且流程结束
     */
    public Integer  handleProcess(String outClassName,Long outClassId,String handleMsg,boolean isAgree){
        Map<String,Object> param =new HashMap<String,Object>();
        Long userId = AdminSessionHolder.getAdminUserId();
      //  param.put("userId",userId );
        param.put("outClassId",outClassId);
        param.put("outClassName",outClassName);
        param.put("sort","sequence");
        param.put("order","ASC");
        param.put("status",1);
        //param.put("order","sequence");
        List<SystemProcessDetail> processDetails = processDetailService.list(param);
        if(ListUtil.isNotNull(processDetails)){
          //
             SystemProcessDetail processDetail=processDetails.get(0);
            // logger.info("当前节点用户ID"+processDetail.getUserId());
            logger.info("登陆用户ID"+userId);
            /* if(processDetail.getStatus()!=1){
                return -3;
            }*/
            //当前审核节点用户信息匹配
            if(processDetail.getUserId().longValue()!=userId.longValue()){
                return -4;
            }
            /*//是否已经操作过。当前节点
            if(processDetail.getStatus()!=1){
                return -3;
            }*/

         //   if()
           // if(processDetail)
            Integer processDetailStatus = isAgree?3:2;
            processDetail.setStatus(processDetailStatus);
            processDetail.setHandleMsg(handleMsg);
            processDetailService.updateExceptEmpty(processDetail.getId(),processDetail);
            //1，如果是驳回操作。流程结束
           // SystemProcess process =super.getById(processDetail.getProcessId());
            SystemProcess process  = new SystemProcess();
            if(!isAgree){
              // SystemProcess process  = new SystemProcess();
               //process.setId(processDetail.getProcessId());
               process.setStatus(2);
               process.setCurrentUserId(0l);
                super.updateExceptEmpty(processDetail.getProcessId(),process);
                return 1;
            }else{
                //2,如果是同意操作，并且流程下所有的节点已经走完。流程结束
                //  boolean processIsEnd=true;
                param.clear();
                param.put("id !=",processDetail.getId());
                param.put("processId",processDetail.getProcessId());
                param.put("status",1);
                param.put("isDeleted",0);
                if(ListUtil.isNull(processDetailService.list(param))){
                    process.setStatus(2);
                    process.setCurrentUserId(0l);
                    super.updateExceptEmpty(processDetail.getProcessId(),process);
                   // super.update(processDetail.getProcessId(),"status",2);
                    //审核流程已结束，
                    return 1;
                }

                super.update(processDetail.getProcessId(),"currentUserId",processDetails.get(1).getUserId());
                //审核流程未结束，只进行了若干节点
                return 0;
            }


        }else{
            //找不到用户的待审核记录
            return -2;
        }

          //  return 0;
    }

    /**
     * 分页获取所有流程信息
     * @param request
     * @return
     */
    public PageResult<SystemProcess> selectProcess(HttpServletRequest request){
        Map<String,Object> param =new HashMap<String, Object>();
        param.put("isDeleted", 0);
        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"number","title","type");
        PageResult<SystemProcess> result=super.containpageQuery(request,containsparam,param);
        //匹配当前节点人员
        List<Long> userIds = new ArrayList<Long>();
        for(SystemProcess process:result.getData()){
            userIds.add(process.getCurrentUserId());
        }
        param.clear();
        if(ListUtil.isNotNull(userIds)){
            param.clear();
            param.put("isDeleted",0);
            param.put("id in",userIds);
            List<SystemUser> users =userService.list(param);
            for(SystemProcess process:result.getData()){
                for(SystemUser user:users){
                    if(LongUtil.isNotZreo(process.getCurrentUserId())&&
                            process.getCurrentUserId().longValue()==user.getId()){
                        process.setCurrentUserName(user.getName());
                        break;
                    }

                }
            }
        }



        return result;
    }
    /**
     * 分页获取所有流程信息
     * @param request
     * @return
     */
    public PageResult<SystemProcess> selectProcessCurrent(HttpServletRequest request){
        Long userId=AdminSessionHolder.getAdminUserId();
        Map<String,Object> param =new HashMap<String, Object>();
        param.put("isDeleted", 0);
        param.put("currentUserId",userId);
        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"");
        PageResult<SystemProcess> result=super.containpageQuery(request,containsparam,param);




        return result;
    }

    public static String generateNumber(String prefix){
        StringBuilder orderNo =new StringBuilder();
        Date now = new Date();
        String year = String.valueOf(now.getYear()+1900);
        String month= (now.getMonth()+1)<10?"0"+String.valueOf(now.getMonth()+1):String.valueOf(now.getMonth()+1);
        String day = now.getDate()<10?"0"+String.valueOf(now.getDate()):String.valueOf(now.getDate());
        if(StringUtils.isNotEmpty(prefix)){
            orderNo.append(prefix);
        }

        //年月日
        orderNo.append(year);
        orderNo.append(month);
        orderNo.append(day);
        //毫秒时间戳后6位
        String times = String.valueOf(new Date().getTime());
        times=times.substring(times.length()-4,times.length());
        orderNo.append(times);
        //6位随机数
        StringBuilder fourNumber = new StringBuilder();
        for(int i=0;i<6;i++){
            Random random1 = new Random();
            fourNumber.append(Math.abs(random1.nextInt(10)));
        }
        orderNo.append(fourNumber);
        return orderNo.toString();
    }



}
